using Microsoft.Ccr.Core;
using Microsoft.Dss.Core;
using Microsoft.Dss.Core.Attributes;
using Microsoft.Dss.ServiceModel.Dssp;
using Microsoft.Dss.Core.DsspHttp;
using Microsoft.Dss.Core.DsspHttpUtilities;
using Microsoft.Dss.ServiceModel.DsspServiceBase;
using Microsoft.Robotics.PhysicalModel.Proxy;
using System;
using System.Net;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Security.Permissions;
using xml = System.Xml;
using W3C.Soap;

using analog = Microsoft.Robotics.Services.AnalogSensor.Proxy;
using analogArray = Microsoft.Robotics.Services.AnalogSensorArray.Proxy;
using vex = VEXRobotics.Proxy;
using submgr = Microsoft.Dss.Services.SubscriptionManager;

namespace VEXService.LineTracker
{
    /// <summary>
    /// Line tracker Sensor Port
    /// </summary>
    [ServicePort]
    public class VEXLineTrackerOperations : PortSet<
        DsspDefaultLookup,
        DsspDefaultDrop,
        Get,
        analogArray.Replace,
        analogArray.Subscribe,
        analogArray.ReliableSubscribe,
        HttpGet,
        HttpPost>
    {
    }

    /// <summary>
    /// Get the VEX Line Tracker Sensor State
    /// </summary>
    [Description("Gets the current state of the VEX Line Tracker Sensor.")]
    public class Get : Get<GetRequestType, PortSet<VEXLineTrackerState, Fault>>
    {
    }

    /// <summary>
    /// Additional configuration which is necessary to 
    /// configure a VEX Line Tracker sensor.
    /// </summary>
    [DataContract]
    public class VEXLineTrackerState : IDssSerializable, ICloneable
    {
        private vex.SensorPort _sensorPortRight;
        private vex.SensorPort _sensorPortCenter;
        private vex.SensorPort _sensorPortLeft;
        private string _name;
        private int _Right;
        private int _Center;
        private int _Left;
        private DateTime _TimeStamp;
        private Pose _Pose;


        public VEXLineTrackerState()
        {
            _TimeStamp = DateTime.MinValue;
            _Pose = new Pose();
        }

        /// <summary>
        /// Indentifies the VEX Sensor Port in which right is plugged.
        /// </summary>
        [DataMember]
        [Description("The sensor port in which the Right sensor is plugged.")]
        public vex.SensorPort SensorPortRight
        {
            get { return _sensorPortRight; }
            set { _sensorPortRight = value; }
        }

        /// <summary>
        /// Indentifies the VEX Sensor Port in which center is plugged.
        /// </summary>
        [DataMember]
        [Description("The sensor port in which the Center sensor is plugged.")]
        public vex.SensorPort SensorPortCenter
        {
            get { return _sensorPortCenter; }
            set { _sensorPortCenter = value; }
        }

        /// <summary>
        /// Indentifies the VEX Sensor Port in which left is plugged.
        /// </summary>
        [DataMember]
        [Description("The sensor port in which the Left sensor is plugged.")]
        public vex.SensorPort SensorPortLeft
        {
            get { return _sensorPortLeft; }
            set { _sensorPortLeft = value; }
        }

        /// <summary>
        /// The name of this sensor
        /// </summary>
        [DataMember]
        [Description("The descriptive name for this sensor.")]
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        // Summary:
        //  Right value
        [Browsable(false)]
        [Description("Current Right value")]
        [DataMember(Order = -1)]
        public int Right
        {
            get { return _Right; }
            set { _Right = value; }
        }

        // Summary:
        //  Center value
        [Browsable(false)]
        [Description("Current Center value")]
        [DataMember(Order = -1)]
        public int Center
        {
            get { return _Center; }
            set { _Center = value; }
        }

        // Summary:
        //  Left value
        [Browsable(false)]
        [Description("Current Left value")]
        [DataMember(Order = -1)]
        public int Left
        {
            get { return _Left; }
            set { _Left = value; }
        }

        //
        // Summary:
        //     Timestamp of this sample
        [DefaultValue(typeof(DateTime), "0001-01-01T00:00:00")]
        [Description("Identifies the timestamp of the accelerometer reading.")]
        [Browsable(false)]
        [DataMember(Order = -1, XmlOmitDefaultValue = true)]
        public DateTime TimeStamp
        {
            get { return _TimeStamp; }
            set { _TimeStamp = value; }
        }

        /// <summary>
        /// Pose of the bumper
        /// </summary>
        [DataMember]
        [Description("The position and orientation of the accelerometer.")]
        public Pose Pose
        {
            get { return _Pose; }
            set { _Pose = value; }
        }

        private analog.AnalogSensorState BuildSensor(int port, double value, Pose pose)
        {
            analog.AnalogSensorState sensor = new analog.AnalogSensorState();
            sensor.HardwareIdentifier = port;
            sensor.RawMeasurement = value;
            sensor.RawMeasurementRange = 1024;
            sensor.NormalizedMeasurement = sensor.RawMeasurement / sensor.RawMeasurementRange;
            sensor.Pose = pose;
            sensor.TimeStamp = TimeStamp;
            return sensor;
        }

        /// <summary>
        /// Transform current state to the specified generic state.
        /// </summary>
        /// <param name="genericState"></param>
        /// <returns></returns>
        public analogArray.AnalogSensorArrayState ToGenericState(analogArray.AnalogSensorArrayState genericState)
        {
            genericState.Sensors.Clear();
            genericState.Sensors.Add(BuildSensor((int) SensorPortRight, Right, Pose));
            genericState.Sensors.Add(BuildSensor((int) SensorPortCenter, Center, Pose));
            genericState.Sensors.Add(BuildSensor((int) SensorPortLeft, Left, Pose));
            return genericState;
        }
        
        /// <summary>
        /// Copy generic state to this state, transforming data members.
        /// </summary>
        /// <param name="genericState"></param>
        public void FromGenericState(analogArray.AnalogSensorArrayState genericState)
        {
            this.TimeStamp = genericState.Sensors[0].TimeStamp;
            this.Right = (int) genericState.Sensors[0].RawMeasurement;
            this.Center = (int) genericState.Sensors[1].RawMeasurement;
            this.Left = (int) genericState.Sensors[2].RawMeasurement;
        }


        #region IDssSerializable

        /// <summary>
        /// Copy To Analog Input sensor state
        /// </summary>
        public virtual void CopyTo(IDssSerializable target)
        {
            VEXLineTrackerState typedTarget = target as VEXLineTrackerState;

            if (typedTarget == null)
                throw new ArgumentException("CopyTo({0}) requires type {0}", this.GetType().FullName);

            typedTarget.Center = this.Center;
            typedTarget.Left = this.Left;
            typedTarget.Name = this.Name;
            typedTarget.Pose = this.Pose;
            typedTarget.Right = this.Right;
            typedTarget.SensorPortCenter = this.SensorPortCenter;
            typedTarget.SensorPortLeft = this.SensorPortLeft;
            typedTarget.SensorPortRight = this.SensorPortRight;
            typedTarget.TimeStamp = this.TimeStamp;
        }

        /// <summary>
        /// Clone the VEX Line Tracker State
        /// </summary>
        /// <returns></returns>
        public object Clone()
        {
            VEXLineTrackerState clone = new VEXLineTrackerState();
            clone.Center = this.Center;
            clone.Left = this.Left;
            clone.Name = this.Name;
            clone.Pose = this.Pose;
            clone.Right = this.Right;
            clone.SensorPortCenter = this.SensorPortCenter;
            clone.SensorPortLeft = this.SensorPortLeft;
            clone.SensorPortRight = this.SensorPortRight;
            clone.TimeStamp = this.TimeStamp;

            return clone;
        }

        /// <summary>
        /// Serialize
        /// </summary>
        public virtual void Serialize(System.IO.BinaryWriter writer)
        {
            writer.Write(this.Center);
            writer.Write(this.Left);
            writer.Write(this.Name);
            Pose.Serialize(writer);
            writer.Write(this.Right);
            writer.Write((int)this.SensorPortCenter);
            writer.Write((int)this.SensorPortLeft);
            writer.Write((int)this.SensorPortRight);
            Microsoft.Dss.Services.Serializer.BinarySerializationHelper.SerializeDateTime(TimeStamp, writer);
        }

        /// <summary>
        /// Deserialize
        /// </summary>
        public virtual object Deserialize(System.IO.BinaryReader reader)
        {
            this.Center = reader.ReadInt32();
            this.Left = reader.ReadInt32();
            this.Name = reader.ReadString();
            Pose.Deserialize(reader);
            this.SensorPortCenter = (vex.SensorPort)reader.ReadInt32();
            this.SensorPortLeft = (vex.SensorPort)reader.ReadInt32();
            this.SensorPortRight = (vex.SensorPort)reader.ReadInt32();
            TimeStamp = Microsoft.Dss.Services.Serializer.BinarySerializationHelper.DeserializeDateTime(reader);

            return this;
        }
        #endregion
    }

    /// <summary>
    /// VEX Accelerometer Sensor Contract 
    /// </summary>
    public sealed class Contract
    {
        public const string Identifier = "http://schemas.vexrobotics.com/2011/09/vexservice.linetracker.html";
    }

    [Contract(Contract.Identifier)]
    [AlternateContract(analogArray.Contract.Identifier)]
    [DisplayName("VEX Line Tracker")]
    [Description("Provides access to the VEX Line Tracker.")]
    [DssServiceDescription("http://msdn.microsoft.com/en-us/library/dd145245.aspx")]
    [DssCategory(vex.VEXCategories.VEX)]
    public class VEXLineTrackerService : DsspServiceBase
    {
        /// <summary>
        /// XSLT Transform to use for display
        /// </summary>
        [EmbeddedResource("VEXService.Config.LineTracker.xslt")]
        private string _transform = null;

        /// <summary>
        /// Sensor state
        /// </summary>
        [InitialStatePartner(Optional = true, ServiceUri = ServicePaths.Store + @"/VEX.LineTracker.config.xml")]
        private VEXLineTrackerState _State = new VEXLineTrackerState();

        /// <summary>
        /// Service port
        /// </summary>
        [ServicePort("/VEX/LineTracker", AllowMultipleInstances = true)]
        private VEXLineTrackerOperations _mainPort = new VEXLineTrackerOperations();

        /// <summary>
        /// Alternate port for the generic port
        /// </summary>
        [AlternateServicePort("/analogarray",
            AllowMultipleInstances = true,
            AlternateContract = analogArray.Contract.Identifier)]
        private analogArray.AnalogSensorOperations _genericPort = new analogArray.AnalogSensorOperations();

        /// <summary>
        /// Port to talk with the VEX controller
        /// </summary>
        [Partner("VEX", Contract = vex.Contract.Identifier,
            CreationPolicy = PartnerCreationPolicy.UseExistingOrCreate,
            Optional = false)]
        private vex.VEXOperations _vexPort = new vex.VEXOperations();

        /// <summary>
        /// VEX Notifications
        /// </summary>
        vex.VEXOperations _notificationPort = new vex.VEXOperations();

        /// <summary>
        /// HTTP helper
        /// </summary>
        DsspHttpUtilitiesPort _httpUtilities = new DsspHttpUtilitiesPort();

        /// <summary>
        /// Subscription manager
        /// </summary>
        [Partner("SubMgr", Contract = submgr.Contract.Identifier,
            CreationPolicy = PartnerCreationPolicy.CreateAlways,
            Optional = false)]
        private submgr.SubscriptionManagerPort _subMgrPort = new submgr.SubscriptionManagerPort();

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="creationPort"></param>
        public VEXLineTrackerService(DsspServiceCreationPort creationPort)
            : base(creationPort)
        {
        }

        #region Initialization Code

        /// <summary>
        /// Startup
        /// </summary>
        protected override void Start()
        {
            LogVerbose(LogGroups.Console, "Configuring VEX Line Tracker... ");

            #region Initialize Service State
            if (_State == null)
            {
                _State = new VEXLineTrackerState();
                SaveState(_State);
            }
            #endregion

            base.Start();

            #region Initialize Service State
            // Reset the controller to know about our configuration
            Port<bool> donePort = new Port<bool>();
            SpawnIterator<Port<bool>>(donePort, InitializeKnownConnection);
            Activate(Arbiter.Receive(false, donePort,
                delegate(bool success)
                {
                    if (success)
                    {
                        // display HTTP service Uri
                        LogInfo(LogGroups.Console, "Service uri: ");
                    }
                    else
                    {
                        LogError(LogGroups.Console, "VEX Line Tracker service failed to start.");
                        _mainPort.Post(new DsspDefaultDrop());
                    }
                }));
            #endregion

            // Needed for HttpPost
            _httpUtilities = DsspHttpUtilitiesService.Create(Environment);
        }

        /// <summary>
        /// Initialize this object based upon the current state.  Additionally,
        /// update the controller to our configuration
        /// </summary>
        /// <param name="donePort"></param>
        /// <returns></returns>
        private IEnumerator<ITask> InitializeKnownConnection(Port<bool> donePort)
        {
            bool serviceSuccess = true;

            // Configure default state
            if (null == _State)
            {
                _State = new VEXLineTrackerState();
            }
            bool aPortSetup = false;
            if (_State.SensorPortRight != vex.SensorPort.SensorPort_None)
            {
                // Configure default state
                vex.SelectivePortConfigure newConfig = new vex.SelectivePortConfigure();
                newConfig.Body.Port = _State.SensorPortRight;
                newConfig.Body.Type = vex.SensorDefinition.SensorType.LineTracker;
                
                _vexPort.Post(newConfig);
                yield return Arbiter.Choice(newConfig.ResponsePort,
                    delegate(DefaultReplaceResponseType response)
                    {
                        aPortSetup = true;
                    },
                    delegate(Fault fault)
                    {
                        serviceSuccess = false;
                        LogError(LogGroups.Console, "Failed to update VEX service configuration", fault);
                    });
            }
            if(_State.SensorPortCenter != vex.SensorPort.SensorPort_None)
            {
                vex.SelectivePortConfigure newConfig = new vex.SelectivePortConfigure();
                newConfig.Body.Port = _State.SensorPortCenter;
                newConfig.Body.Type = vex.SensorDefinition.SensorType.LineTracker;

                _vexPort.Post(newConfig);
                yield return Arbiter.Choice(newConfig.ResponsePort,
                    delegate(DefaultReplaceResponseType response)
                    {
                        aPortSetup = true;
                    },
                    delegate(Fault fault)
                    {
                        serviceSuccess = false;
                        LogError(LogGroups.Console, "Failed to update VEX service configuration", fault);
                    });
            }
            if (_State.SensorPortLeft != vex.SensorPort.SensorPort_None)
            {
                vex.SelectivePortConfigure newConfig = new vex.SelectivePortConfigure();
                newConfig.Body.Port = _State.SensorPortLeft;
                newConfig.Body.Type = vex.SensorDefinition.SensorType.LineTracker;

                _vexPort.Post(newConfig);
                yield return Arbiter.Choice(newConfig.ResponsePort,
                    delegate(DefaultReplaceResponseType response)
                    {
                        aPortSetup = true;
                    },
                    delegate(Fault fault)
                    {
                        serviceSuccess = false;
                        LogError(LogGroups.Console, "Failed to update VEX service configuration", fault);
                    });
            }

            // Make sure that some ports are selected.
            if (false == aPortSetup)
            {
                LogError(_State.Name + ": No sensor ports selected");
            }

            // Subscribe to VEX for notifications
            if (serviceSuccess)
            {
                serviceSuccess = false;
                if (aPortSetup)
                {
                    SaveState(_State);
                    Port<bool> subscribeDonePort = new Port<bool>();
                    SpawnIterator<Port<bool>>(subscribeDonePort, SubscribeToVEX);
                    yield return (Arbiter.Receive<bool>(false, subscribeDonePort,
                        delegate(bool success)
                        {
                            serviceSuccess = success;
                        }));
                }
            }

            donePort.Post(serviceSuccess);
            yield break;
        }

        /// <summary>
        /// Subscribe to appropriate sensor type and port on VEX
        /// Hook up notifications
        /// and then post success or failure
        /// <param name="successPort"></param>
        /// </summary>
        private IEnumerator<ITask> SubscribeToVEX(Port<bool> successPort)
        {
            // Create a custom subscription request
            vex.CustomSubscribeRequestType request = new vex.CustomSubscribeRequestType();

            // Select only the sensor and port we want
            // NOTE: this name must match the VEX sensor name.
            request.Sensors = new List<vex.SensorDefinition>();
            if(_State.SensorPortRight != vex.SensorPort.SensorPort_None)
            {
                vex.SensorDefinition sensor = new vex.SensorDefinition();
                sensor.Type = vex.SensorDefinition.SensorType.AnalogInput;
                sensor.Port = _State.SensorPortRight;
                request.Sensors.Add(sensor);
            }
            if (_State.SensorPortCenter != vex.SensorPort.SensorPort_None)
            {
                vex.SensorDefinition sensor = new vex.SensorDefinition();
                sensor.Type = vex.SensorDefinition.SensorType.AnalogInput;
                sensor.Port = _State.SensorPortCenter;
                request.Sensors.Add(sensor);
            }
            if (_State.SensorPortLeft != vex.SensorPort.SensorPort_None)
            {
                vex.SensorDefinition sensor = new vex.SensorDefinition();
                sensor.Type = vex.SensorDefinition.SensorType.AnalogInput;
                sensor.Port = _State.SensorPortLeft;
                request.Sensors.Add(sensor);
            }

            // Subscribe to the VEX and wait for a response
            bool subscribed = false;
            yield return
                Arbiter.Choice(_vexPort.SelectiveSubscribe(request, _notificationPort),
                    delegate(SubscribeResponseType Rsp)
                    {
                        //Subscription was successful, start listening for sensor change notifications
                        Activate(
                            Arbiter.Receive<vex.Update>(true, _notificationPort, SensorNotificationHandler)
                        );

                        //update our state with subscription status
                        subscribed = true;
                    },
                    delegate(Fault fault)
                    {
                        LogError("Line Tracker subscription failed", fault);
                        successPort.Post(false);
                    }
                );

            successPort.Post(subscribed);
            yield break;
        }

        #endregion

        #region Internal Port Handlers

        /// <summary>
        /// Handle sensor update message from VEX
        /// </summary>
        private void SensorNotificationHandler(vex.Update notify)
        {
            // Update state
            bool changed = false;
            _State.TimeStamp = DateTime.Now;

            if(_State.SensorPortRight != vex.SensorPort.SensorPort_None)
            {
                int newValue = notify.Body.PortSensors.Sensors[(int)_State.SensorPortRight - 1].Value;
                changed |= (_State.Right != newValue);
                _State.Right = newValue;
            }
            if(_State.SensorPortCenter != vex.SensorPort.SensorPort_None)
            {
                int newValue = notify.Body.PortSensors.Sensors[(int)_State.SensorPortCenter - 1].Value;
                changed |= (_State.Center != newValue);
                _State.Center = newValue;
            }
            if(_State.SensorPortLeft != vex.SensorPort.SensorPort_None)
            {
                int newValue = notify.Body.PortSensors.Sensors[(int)_State.SensorPortLeft - 1].Value;
                changed |= (_State.Left != newValue);
                _State.Left = newValue;
            }

            // Notify subscribers on any state change
            if (changed)
            {
                analogArray.AnalogSensorArrayState genericState = new analogArray.AnalogSensorArrayState();
                genericState.Sensors = new List<analog.AnalogSensorState>();
                SendNotification<analog.Replace>(_subMgrPort, _State.ToGenericState(genericState));
            }
        }
        #endregion

        #region Standard Operation Handlers

        /// <summary>
        /// Get the state
        /// </summary>
        /// <param name="get"></param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Concurrent)]
        public IEnumerator<ITask> GetHandler(Get get)
        {
            get.ResponsePort.Post(_State);
            yield break;
        }
        [ServiceHandler(ServiceHandlerBehavior.Concurrent, PortFieldName = "_genericPort")]
        public IEnumerator<ITask> GetHandler(analogArray.Get get)
        {
            analogArray.AnalogSensorArrayState genericState = new analogArray.AnalogSensorArrayState();
            genericState.Sensors = new List<analog.AnalogSensorState>();
            get.ResponsePort.Post(_State.ToGenericState(genericState));
            yield break;
        }

        /// <summary>
        /// Get the state to HTTP display
        /// </summary>
        /// <param name="httpGet">Response port to post the state</param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Concurrent)]
        [ServiceHandler(ServiceHandlerBehavior.Concurrent, PortFieldName = "_genericPort")]
        public IEnumerator<ITask> HttpGetHandler(HttpGet httpGet)
        {
            httpGet.ResponsePort.Post(new HttpResponseType(
                HttpStatusCode.OK,
                _State,
                _transform)
            );
            yield break;
        }

        /// <summary>
        /// HttpPost Handler
        /// </summary>
        /// <param name="submit"></param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Exclusive)]
        public virtual IEnumerator<ITask> HttpPostHandler(HttpPost httpPost)
        {
            // Use helper to read form data
            ReadFormData readForm = new ReadFormData(httpPost);
            _httpUtilities.Post(readForm);

            // Wait for result
            Activate(Arbiter.Choice(readForm.ResultPort,
                delegate(NameValueCollection parameters)
                {
                    if (parameters["Name"] != null)
                    {
                        // Update our state variables
                        _State.Name = parameters["Name"];
                    }
                    HttpPostSuccess(httpPost);
                },
                delegate(Exception fault)
                {
                    LogError(fault.Message);
                    HttpPostFailure(httpPost, fault.Message);
                })
            );
            yield break;
        }

        /// <summary>
        /// Send Http Post Success Response
        /// </summary>
        /// <param name="httpPost"></param>
        private void HttpPostSuccess(HttpPost httpPost)
        {
            HttpResponseType rsp =
                new HttpResponseType(HttpStatusCode.OK, _State, _transform);
            httpPost.ResponsePort.Post(rsp);
        }

        /// <summary>
        /// Send Http Post Failure Response
        /// </summary>
        /// <param name="httpPost"></param>
        /// <param name="failureReason"></param>
        private static void HttpPostFailure(HttpPost httpPost, string failureReason)
        {
            HttpResponseType rsp =
                new HttpResponseType(HttpStatusCode.ExpectationFailed, failureReason);
            httpPost.ResponsePort.Post(rsp);
        }
        
        /// <summary>
        /// Replace the state with the given update
        /// </summary>
        /// <param name="replace">Replacement state</param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Exclusive)]
        [ServiceHandler(ServiceHandlerBehavior.Exclusive, PortFieldName = "_genericPort")]
        public IEnumerator<ITask> ReplaceHandler(analogArray.Replace replace)
        {
            if (replace.Body.Sensors.Count != 3)
            {
                Fault fault = Fault.FromException(new InvalidOperationException("Invalid number of sensors"));
                replace.ResponsePort.Post(fault);
                yield break;
            }
            if ((int)_State.SensorPortLeft != replace.Body.Sensors[0].HardwareIdentifier ||
                (int)_State.SensorPortCenter != replace.Body.Sensors[1].HardwareIdentifier ||
                (int)_State.SensorPortRight != replace.Body.Sensors[2].HardwareIdentifier)
            {
                Fault fault = Fault.FromException(new InvalidOperationException("Cannot reassign sensor ports"));
                replace.ResponsePort.Post(fault);
                yield break;
            }

            _State.FromGenericState(replace.Body);
            SaveState(_State);

            analogArray.AnalogSensorArrayState genericState = new analogArray.AnalogSensorArrayState();
            genericState.Sensors = new List<analog.AnalogSensorState>();
            SendNotification<analogArray.Replace>(_subMgrPort, _State.ToGenericState(genericState));
            replace.ResponsePort.Post(DefaultReplaceResponseType.Instance);
            yield break;
        }

        /// <summary>
        /// Subscribe to updates
        /// </summary>
        /// <param name="subscribe"></param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Exclusive)]
        [ServiceHandler(ServiceHandlerBehavior.Exclusive, PortFieldName = "_genericPort")]
        public IEnumerator<ITask> SubscribeHandler(analogArray.Subscribe subscribe)
        {
            yield return Arbiter.Choice(
                SubscribeHelper(_subMgrPort, subscribe.Body, subscribe.ResponsePort),
                delegate(SuccessResult success)
                {
                    analogArray.AnalogSensorArrayState genericState = new analogArray.AnalogSensorArrayState();
                    genericState.Sensors = new List<analog.AnalogSensorState>();
                    SendNotification<analogArray.Replace>(_subMgrPort, subscribe.Body.Subscriber, new analogArray.Replace(_State.ToGenericState(genericState)));
                },
                delegate(Exception fault)
                {
                    LogError(fault);
                }
            );
        }

        /// <summary>
        /// ReliableSubscribe Handler
        /// </summary>
        /// <param name="subscribe"></param>
        /// <returns></returns>
        [ServiceHandler(ServiceHandlerBehavior.Exclusive)]
        [ServiceHandler(ServiceHandlerBehavior.Exclusive, PortFieldName = "_genericPort")]
        public IEnumerator<ITask> ReliableSubscribeHandler(analogArray.ReliableSubscribe subscribe)
        {
            yield return Arbiter.Choice(
                SubscribeHelper(_subMgrPort, subscribe.Body, subscribe.ResponsePort),
                delegate(SuccessResult success)
                {
                    analogArray.AnalogSensorArrayState genericState = new analogArray.AnalogSensorArrayState();
                    genericState.Sensors = new List<analog.AnalogSensorState>();
                    SendNotification<analogArray.Replace>(_subMgrPort, subscribe.Body.Subscriber, _State.ToGenericState(genericState));
                },
                delegate(Exception fault)
                {
                    LogError(fault);
                }
            );
        }

        #endregion
    }
}
